<template>

    <div >
      <div class="tags">
        <div class="tagsName">
            <!-- <Tag type="border" size="large" class="pester">所有</Tag> -->
            <!-- <Tag type="border" size="large" class="pester" checkable :class="{'tagclass':ite.isactive}":class="isactive?'tagclass':''"  v-for="ite in tagsList" :value="ite.id" :key="ite.id" @on-change="changeTag(ite)">{{ite.name}}</Tag> -->
            <Button class="pester" v-for="(ite,index) in tags" :value="ite.id" :key="ite.id" :class="{'tagclass':ite.isactive,active: currentIndex === index}"  @click="changeTag(ite,index)">{{ite.name}}</Button>
          </div>
        <div class="moreBut">
          <Button @click="changeMore" v-if="tagsList.length>20" v-show="tagsShow">加载更多</Button>
        </div>
      </div>
      <div class="" v-if="imgList.length>0">
         <Scroll :on-reach-bottom="handleReachBottom" :height="500">
          <div class="imageClub" v-if="!show">
            <template>
              <div class="imageCard" v-for="(item,index) in imgList" :key="index" >
                <div class="cardInfo" >
                  <div class="imageurl" @mouseover="changemodal(item)" @mouseout="changeout(item)" @click="changeClick(item,index)"  >
                    <a target="_self" href="javascript:;" :thislink='item.linkUrl'><img :src= item.path  class="canvasImg"  /></a>
                    <div v-show="item.show" class="showstyle">
                      <span class="showtype">{{item.extension}}</span>
                    </div>
                  </div>
                  <div class="cardButton">
                      <span style="padding-top:10px">{{item.width}}*{{item.height}}</span>
                      <span style="padding-top:10px"><Icon type="ios-eye-outline" />{{item.click}}</span>
                      <div>
                        <!-- <Dropdown @on-click="changelist(item,index)">
                            <a href="javascript:void(0)">
                              {{item.linkUrl}}
                              <Icon type="ios-arrow-down"></Icon>
                            </a>
                          <DropdownMenu slot="list" transfer selected v-model="value" >
                            <DropdownItem  v-for="(it,idx) in item.selectList" :key="idx" :value="it.value" >{{it.label}}</DropdownItem>
                        </DropdownMenu>
                          </Dropdown> -->
                        <Select v-model="item.linkUrl" style="width:80px" @on-change="changelink" >
                            <Option v-for="(it,idx) in item.selectList" :key="idx" :value="it.value" >{{it.label}}</Option>
                        </Select>
                      </div>

                  </div>
                  <div class="cardsmall">
                    <Button size="small" @click="changedel(item)" v-hasC="{name: '-v1-material-img-img-del',flag: '/v1/material/img/img-del'}">删除</Button>
                    <Button size="small" @click="changetype(item)" v-hasC="{name: '-v1-material-img-cates-change',flag: '/v1/material/img/cates-change'}">变更类别</Button>
                    <Button size="small" @click="changeImg(item)" v-hasC="{name: '-v1-material-img-img-change',flag: '/v1/material/img/img-change'}">图片替换</Button>
                  </div>
                  <div class="boxFotter">
                    <span>标签：</span>
                    <Input v-model="item.remarks" placeholder="请输入标签" style="width: 200px"  @on-blur="changeMark(item)"/>
                  </div>
                </div>
              </div>
            </template>

            <!-- 更改图片类型 -->
            <Modal v-model="modalstatus" title="更改当前图类别" width="500">
                <Form :ref='modalForm' :model='modalForm' :rules="rules">
                    <FormItem >
                      <Select v-model="modalForm.tagIds" style="width:400px" placeholder="请选择上传类别" filterable multiple>
                        <Option v-for="item in typeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                      </Select>
                    </FormItem>
                </Form>
                <div slot='footer' class="footer">
                    <!-- <Button @click='canceledit(modalForm)'>取消</Button> -->
                    <Button  type='primary' :loading="subloading" @click='submitedit(modalForm)'>保存</Button>
              </div>
            </Modal>
            <!-- 图片替换 -->
            <Modal v-model="imgstatus" title="更改当前图片" width="450">
              <Upload
                ref='upload'
                :format="['jpg','png','gif']"
                :action="requestAction"
                :headers="{'Authorization': 'Bearer ' + token,'projectid':project}"
                :on-progress="onprogress"
                :on-success="(res) => upSuccess(res)"

                :show-upload-list="false"
                type="drag"
                >
                <div style="padding: 20px 0" v-if="!imgurl">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>点击上传图片</p>
                </div>
                <div v-else>
                  <img :src="imgurl" width="100%" height="350px">
                </div>
              </Upload>
              <div slot='footer' class="footer">
                    <!-- <Button @click='canceledit(modalForm)'>取消</Button> -->
                  <Button  type='primary' :loading="imageing" @click='saveImg'>保存</Button>
              </div>
            </Modal>
          </div>
         </Scroll>
      </div>
      <div v-if="imgList.length==0 && show===false" class="resdata">
        <span>暂无数据</span>
      </div>
       <Spin size="large" fix  v-show="show"></Spin>
    </div>
    <!-- <div v-if="isbuay">没有更多了哟</div> -->

</template>
 <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script>
    import { getimgList, imgdel, getimgtype, materialtype, imageChage, tagsAdd, getclickAdd, getObjectURL } from '@/api/myuplod.js'
    // import template from '../../../components/search/template.vue'
    import Setting from '@/setting';
    import util from '@/libs/util';
    export default {
        // components: { template },
        props: {
            remark: String
        },
        data () {
            return {
                project: util.storage.get('currentProject'),
                token: util.cookies.get('token'),
                baseUrl: Setting.apiBaseURL,
                requestAction: '',
                imgurl: '',
                imgList: [],
                value: '',
                typeList: [],
                tagsList: [],
                modalstatus: false,
                tags: [],
                modalForm: {
                    tagIds: []
                },
                rules: {
                    tagIds: [{ required: true, message: '请选择更改的类别', trigger: 'change' }]
                },
                subloading: false,
                imgstatus: false,
                imageing: false,
                id: '',
                imgPath: '',
                tag_id: '', // tags搜索
                link: '',
                page: 1,
                currentIndex: 0,
                show:false,
                total:0,
                isbuay:false,
                pageSize:20,
                tagsShow:true
            }
        },
        mounted () {
            this.requestAction = this.baseUrl + `/v1/material/upload/imgs-upload`;
            let that=this
            // window.onscroll=function(){
            //   //获取滚动条到顶部的位置：
            //   let scrollTop=document.documentElement.scrollTop||document.body.scrollTop
            //   //获取当前窗口内容可视区
            //   let windowHeight=document.documentElement.clientHeight||document.body.clientHeight
            //   // /获取滚动条的总高度
            //   let scrollHeight=document.documentElement.scrollHeight||document.body.scrollHeight
            //   if(scrollTop+windowHeight==scrollHeight){
            //     //加载数据
            //     this.show=!this.show
            //     that.loadMore()
            //   }
            // }
        },
        created () {
           this.inits()
        },
        methods: {
          inits(){
            this.page=1;
            this.imgList=[];
             this._getimgList();
              this._gettype()
          },
            // 鼠标移动效果
            changemodal (item) {
                item.show = true
            },
            changeout (item) {
                item.show = false
            },
            // 获取类别
            _gettype () {
                materialtype({}).then(res => {
                    this.typeList = res;
                    this.tagsList = res.map(item => ({
                        ...item, isactive: false
                    }));
                    this.tagsList.unshift({
                        id: '',
                        name: '所有'
                    })
                    this.tags = this.tagsList.slice(0, 20);
                }).catch(() => {
                    // this.tableLoading = false
                })
            },
            changeMore () {
                this.tags = this.tagsList
                this.tagsShow=false
            },
            // 切换工具
            changelink () {
                //
            },
            // 切换类型
            changetype (item) {
                this.$set(this.modalForm, 'id', item.id)
                this.modalstatus = true
                this.modalForm.tagIds = []
            },
            // 类别确定
            submitedit (modalForm) {
                this.$refs[modalForm].validate((valid) => {
                    if (valid) {
                        this.subloading = true;
                        let params = {
                            id: this.modalForm.id,
                            tagIds: this.modalForm.tagIds.join(',')
                        }
                        getimgtype(params).then(res => {
                            this.$Message.success('更改成功');
                            this.modalstatus = false;
                            this.subloading = false;
                            this._getimgList()
                        }).catch(() => {
                            this.modalstatus = false;
                            this.subloading = false;
                        })
                    } else {
                        // this.$Message.error('请完善表格。');
                    }
                })
            },
            // tabs切换
            changeTag (ite, index) {
                ite.isactive = !ite.isactive
                ite.showtive = !ite.showtive
                this.currentIndex = index;
                this.tag_id = ite.id
                this.page=1
                this.imgList=[]
                this._getimgList()
            },
            // 获取列表数据
            _getimgList () {
                let params = {
                    tag_id: this.tag_id,
                    remark: this.remark,
                    page: this.page
                }
                this.show=true
                getimgList(params).then(res => {
                  let list = res.list.map(item => ({
                      ...item,
                      show: false,
                      // remarks: '',
                      selectList: [
                          {
                              value: '/swt/',
                              label: '快商通'
                          },
                          {
                              value: '/tell/',
                              label: '电话'
                          },
                          {
                              value: 'javascript:;',
                              label: '其他'
                          }
                      ]
                  }));
                  this.total=res.total
                  this.imgList = this.page === 1 ? list : [...this.imgList, ...list]

                  this.show=false
                  // console.log(this.imgList,'imglist数据')
                  }).catch(() => {
                      // this.tableLoading = false
                  })

            },
            // 删除图片
            changedel (item) {
                this.$Modal.confirm({
                    title: '确定将当前图片删除移入回收站？',
                    // content: '<p>Content of dialog</p><p>Content of dialog</p>',
                    onOk: () => {
                        imgdel({ id: item.id }).then(res => {
                            this.$Message.info('删除成功');
                            this._getimgList()
                        }).catch(() => {
                            // this.$Message.error('删除失败')
                        })
                    },
                    onCancel: () => {
                        // this.$Message.error('')
                    }
                })
            },
            // 图片更换
            changeImg (item) {
                this.id = item.id
                this.imgstatus = true
                this.imgurl = ''
                this.imgPath = ''
            },
            onprogress () {
                //
            },
            upSuccess (response) {
                let url = response.data.map(item => item.img_url)
                this.imgPath = url
                this.imgurl = `${this.baseUrl}/library_image_tmp${url}`
            },
            saveImg () {
                if (this.imgurl) {
                    this.imageing = true;
                    let params = {
                        id: this.id,
                        imgPath: this.imgPath.join('')
                    }
                    imageChage(params).then(res => {
                        this.$Message.success('更改成功');
                        this.imgstatus = false;
                        this.imageing = false;
                        this._getimgList()
                    }).catch(() => {
                        this.imgstatus = false;
                        this.imageing = false;
                    })
                } else {
                    this.$Message.error('请选择图片')
                }
            },
            // 打标签
            changeMark (item) {
                let params = {
                    id: item.id,
                    remark: item.remarks
                }
                tagsAdd(params).then(res => {
                    this.$Message.success('标记成功');
                    // this._getimgList()
                }).catch(() => {

                })
            },
            changeClick (item,index) {
                getclickAdd({ id: item.id }).then(res => {
                    // this.$Message.success('标记成功');
                }).catch(() => {

                })
                 //复制图片
               let img = document.getElementsByClassName("canvasImg")[index];
                this.getSelect(img)
                this.clipboardHandler(img,event)
                // img.addEventListener('mouseenter', this.clipboardHandler);
                // this.clipboardHandler(img)
                let pHandler = this.clipboardHandler.bind(null, 'p');
              var div =  document.getElementsByClassName("imageurl")[index];
              div.addEventListener('click', pHandler);
            },
               //复制图片
            getSelect(targetNode){
              // debugger
              if (window.getSelection) {
                //chrome等主流浏览器
                var selection = window.getSelection();
                var range = document.createRange();
                range.selectNode(targetNode);
                selection.removeAllRanges();
                selection.addRange(range);
              } else if (document.body.createTextRange) {
                //ie
                var range = document.body.createTextRange();
                range.moveToElementText(targetNode);
                range.select();
              }
            },
            clipboardHandler(nodeName,event) {
              // debugger
              event = event || nodeName; //不传参时
              const type = Object.prototype.toString.call(nodeName).replace(/\[object\s|\]/g, '');
              const target = event.target || event.srcElement;

              var result = false;
              switch (type) {
                case 'String':
                  result = (target.nodeName.toLowerCase() === nodeName);
                  break;
                case 'Array':
                  result = nodeName.some(item => target.nodeName.toLowerCase() === item);
                  break;
                case 'Object':
                  nodeName = null;
                default:
                  result = (target.nodeName === 'IMG');
              }

              if (result) {
                this.getSelect(target);
                document.execCommand('copy');
                if(document.execCommand('copy')){
                  // this.$Modal.info({
                  //   title: '温馨提示：',
                  //   content: '复制当前图片已成功'
                  // });
                  // this.$Message.success('复制当前图片已成功')
                  // this.$Message.success({
                  //   content: '当前图片已复制成功',
                  //   duration: 130
                  // });
                  this.$Notice.success({
                    title: '温馨提示：',
                    desc: '复制当前图片已成功'
                  });
                }else{
                  this.$Message.error('复制失败')
                }
                // console.log( document.execCommand('copy'),'copy')
              }
          },
            // 上拉刷新
          handleReachBottom () {
              if(this.page*this.pageSize>=this.total){
                this.show=false,
                this.isbuay=true
                // this.$Message.success('没有更多了哟')
              }else{
                this.show=false
                 this.isbuay=false
                this.page++
                this._getimgList()
              }
              // this.page++
              // this._getimgList()

            },
            //滚动加载更多

        },
    }
</script>
<style scoped>
.tags{

  /* padding:10px 0; */
  border-left:0.5px solid #ccc;
  border-right:0.5px solid #ccc;
  box-shadow: 0px 1px 4px #999;
}
.pester{
 margin:5px;
}
.tagsName{
  padding:10px;
}
.tagclass{
  /* background:#515a6e ;
  color: #fff; */
}
.active {
  background:#515a6e ;
  color: #fff;
 }
.showclass{
   background:none ;
  /* color:#000; */
}
.moreBut{
  text-align: center;
  padding: 0 0 10px 0;
  }
.imageClub{
  position: relative;
  padding: 10px 0 0 20px;
  /* display: flex; */
}
.imageCard{
  width: 280px;
  border-radius: 5px;
  display: inline-block;
  box-shadow: 0 1px 4px rgb(177, 175, 175);
  margin-right: 15px;
  margin-bottom: 15px;
}
  .cardInfo{
    padding: 15px;
  }
  .imageurl{
    width: 100%;
    /* background: rgb(99, 188, 223); */
    height:250px;
    position: relative;
    overflow: hidden;
  }
  .canvasImg{
    width: 100%;
     height:auto;
    /* max-height: 250px; */
    object-fit: contain;
  }
  .cardButton{
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
  }
  .cardsmall{
    display: flex;
     justify-content: space-between;
     padding: 6px 0;
  }
  .boxFotter{
    padding:10px 0;
  }
  .showstyle{
    width: 100%;
    /* height: 100%; */
    position: absolute;
    background: #000;
    left: 0;
    top: 0;
    opacity: .5;
  }
  .showtype{
    position: absolute;
    right:10px;
    top:10px;
    padding: 0px 20px;
    border-radius: 5px;
    background: #515a6e;
    font-size: 16px;
    color: #fff;
  }
  /deep/.ivu-select-single{
    height: 10px;
  }
  .resdata{
    padding: 50px 0;
    text-align: center;
    color: #888;
    font-size: 16px;
  }

</style>
